package org.hd.login.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import org.apache.tomcat.util.codec.binary.Base64;
import org.hd.entities.User;
import org.hd.login.dao.UserDao;
import org.hd.login.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService{

    @Resource
    UserDao userDao;

    /***
     * 获取公钥并检验用户是否存在
     * @param username 用户名
     * @return
     * @throws Exception
     */
    @Override
    public String getPublicKey(String username) throws Exception {
        //获取到用户信息
        //Map<String, String> map = new HashMap<>();

        //User user = userDao.getUser(userName);


        //开始生成钥匙对
        Map<String,String> keymap = SaSecureUtil.rsaGenerateKeyPair();
        //更新钥匙对
        boolean flag = userDao.refreshKey(keymap.get("private"),keymap.get("public"),username);
        //如果更新失败
        if(!flag){
            return null;
        }

        return keymap.get("public");
    }

    /**
     * 比较解密后的密码
     * @param username  用户名
     * @param cipherText  加密后的密码
     * @return
     */
    @Override
    public Map<String,String> compailPassword(String username, String cipherText ) {
        Map<String,String> map = new HashMap<>();
        //获取用户信息
        User user = userDao.getUser(username);

        if(null == user){
            map.put("flag","fail");
            map.put("userId","fail");
            return map;
        }
        String decrypt = null;
        try {
            //64位解码加密后的字符串
            byte[] inputByte = Base64.decodeBase64(cipherText.getBytes("gbk"));
            //base64编码的私钥
            byte[] decoded = Base64.decodeBase64(user.getPrivate_key());
            RSAPrivateKey pri = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, pri);
            decrypt = new String(cipher.doFinal(inputByte));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        if(decrypt.equals(user.getPassword())){
            map.put("flag","success");
            map.put("userId",user.getUser_id());
            map.put("username",user.getUsername());
            return map;
        }
        map.put("flag","fail");
        map.put("userId","fail");

        return map;
    }
}
